class Calendar {
  constructor(config) {
    if (!config || typeof config !== 'object') {
      console.error('配置文件有误')
      return
    }
    this.el = typeof config.el === 'string' ? this.qs(config.el) : config.el
    this.date = config.date || ''
    this.curDayClass = 'current'
    this.isWeekend = config.isWeekend || true
    this.yearSelect = config.yearSelect || 0
    this.monthSelect = config.monthSelect || 0
    this.onChanged = config.onChanged || function () {}
    this.onResult = config.onResult || function () {}
    this.renderTbody()
  }

  qs(id) {
    return document.querySelector(id)
  }

  qsAll(id) {
    return document.querySelectorAll(id)
  }

  getDays(year, month) {
    // 获取月份的天数
    return new Date(year, month, 0).getDate()
  }

  goToNextMonth() {
    if (this.monthSelect++ >= 12) {
      this.yearSelect += 1
      this.monthSelect = 1
    }
    this.renderTbody(this.yearSelect, this.monthSelect)
  }
  goToPrevMonth() {
    if (this.monthSelect-- <= 1) {
      this.yearSelect -= 1
      this.monthSelect = 12
    }
    this.renderTbody(this.yearSelect, this.monthSelect)
  }

  event() {
    let _td = this.qsAll('#calendar td')
    const _this = this
    for (let i = 0; i < _td.length; i++) {
      _td[i].addEventListener('click', function () {
        if (this.dataset.id <= 0) return
        _td.forEach((elem) => {
          elem.classList.remove('selected')
        })
        this.classList.add('selected')
        _this.onResult(_this.yearSelect, _this.monthSelect, +this.dataset.id)
      })
    }
  }

  renderTbody(year, month) {
    let today = new Date(),
      curYear = today.getFullYear(),
      curMonth = today.getMonth() + 1,
      curDate = today.getDate()

    var _date = this.date
      ? this.date.split(/[-\/]/)
      : [new Date().getFullYear(), new Date().getMonth() + 1]

    var _year = +year || +_date[0],
      _month = +month || +_date[1],
      // 当前星期几
      _firstDay = new Date(_year, _month - 1, 1).getDay(),
      _weeks = ['日', '一', '二', '三', '四', '五', '六']

    var thead = '',
      tbody = '',
      result = '',
      isThisMonth = _year === curYear && _month === curMonth ? true : false
    this.yearSelect = _year
    this.monthSelect = _month

    // 渲染星期
    for (var i = 0; i < 7; i++) {
      thead += `<th>${_weeks[i]}</th>`
    }
    thead = `<tr>${thead}</tr>`

    // 渲染天
    for (
      var j = 0, len = _firstDay + this.getDays(_year, _month);
      j < len;
      j++
    ) {
      if (j % 7 === 0) {
        tbody += '<tr>'
      }
      tbody += `<td class="${
        isThisMonth && j - _firstDay + 1 === curDate ? this.curDayClass : ''
      }" data-id="${j - _firstDay + 1}">
        <div><span>${
          j < _firstDay ? '&nbsp;' : j - _firstDay + 1
        }</span></div></td>`
      if ((j !== 0 && (j + 1) % 7 === 0) || j === len - 1) {
        tbody += '</tr>'
      }
    }

    // 渲染日历table

    this.el.innerHTML = `<table>${thead}${tbody}</table>`

    this.event()

    if (this.isWeekend) {
      let arrDom = Array.from(this.qsAll('#calendar tr'))
      arrDom.map((node) => {
        node.children[0] && node.children[0].classList.add('weekend')
        node.children[6] && node.children[6].classList.add('weekend')
      })
    }

    this.onChanged(
      this.yearSelect,
      this.monthSelect,
      this.getDays(this.yearSelect, this.monthSelect)
    )
  }
}

